from django.conf import settings
from django.shortcuts import render
from .models import OAuthQQModel
# Create your views here.
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from .serializers import OAuthQQSerializer
from rest_framework.generics import CreateAPIView


class QQAuthURLView(APIView):
    """提供QQ登录页面网址
    https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=xxx&redirect_uri=xxx&state=xxx
    """
    def get(self, request):

        # next表示从哪个页面进入到的登录页面，将来登录成功后，就自动回到那个页面
        next = request.query_params.get('next')
        if not next:
            next = '/'

        # 获取QQ登录页面网址
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next
        )

        # 获取ＱＱ登陆地址
        login_url = oauth.get_qq_url()

        # 返回地址给前段,login_url　是前段字段
        return Response(
            {
                'login_url':login_url
            }
        )



# class QQLoginView(APIView):
#
#     def get(self,request):
#         # 获取ｃｏｄｅ值
#         code = request.query_params.get("code")
#         if not code:
#             return Response({"message":"缺少ｃｏｄｅ值"},status=401)
#
#
#         # 获取ａccess--token
#         oauth = OAuthQQ(
#             client_id=settings.QQ_CLIENT_ID,
#             client_secret=settings.QQ_CLIENT_SECRET,
#             redirect_uri=settings.QQ_REDIRECT_URI,
#             state=next
#         )
#         # 获取access_token值
#         access_token = oauth.get_access_token(code)
#         #　获取open_id
#         openid = oauth.get_open_id(access_token)
#
#
#
#         # ---------------------进行绑定----------------------------------------------------
#         #1 判断用户有没有绑定过
#         try:
#             qq_oauth=OAuthQQModel.objects.get(openid=openid)
#
#         except:
#             # 未绑定
#             tjs=TJS(settings.SECRET_KEY,300)
#             data={'openid':openid}
#             access_token=tjs.dumps(data).decode()
#             return Response({'access_token':access_token})
#
#         # 绑定过跳转到登录成功页面
#         # 获取user用户
#         user=qq_oauth.user
#
#         jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
#         jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#
#         payload = jwt_payload_handler(user)
#         token = jwt_encode_handler(payload)
#
#         return Response(
#             {
#                 'token':token,
#                 'username':user.username,
#                 'user_id':user.id
#             }
#         )
#
#
#
#
#     # post请求，处理绑定openid业务逻辑　　　　其实这里很像creatＡＰＩVIEW
#
#     def post(self,request):
#         # 获取前段数据
#         data = request.data
#         # 验证数据
#         ser = OAuthQQSerializer(data=data)
#         ser.is_valid(raise_exception=True)
#         # 绑定存数据
#         user = ser.save()
#         # 生成ｔｏｋｅｎ值()
#         jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
#         jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
#         payload = jwt_payload_handler(user)
#         token = jwt_encode_handler(payload)
#
#         # 结果返回
#         return Response(
#             {
#                 "token":token,
#                 "username":user.username,
#                 "user_id":user.id
#
#             }
#         )



class QQLoginView(CreateAPIView):

    serializer_class = OAuthQQSerializer

    def get(self,request):
        # 获取ｃｏｄｅ值
        code = request.query_params.get("code")
        if not code:
            return Response({"message":"缺少ｃｏｄｅ值"},status=401)


        # # 获取ａccess--token
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=next
        )
        # response = request.get("https://graph.qq.com/oauth2.0/token",params={
        #     "grant_type":"authorization_code","client_id":settings.QQ_CLIENT_ID,
        #     "client_secret":settings.QQ_CLIENT_SECRET,"code":code,
        #     "redirect_uri":settings.QQ_REDIRECT_URI
        #     })
        # data = response.text

        # 获取access_token值
        access_token = oauth.get_access_token(code)
        #　获取open_id
        openid = oauth.get_open_id(access_token)



        # ---------------------进行绑定----------------------------------------------------
        #1 判断用户有没有绑定过
        try:
            qq_oauth=OAuthQQModel.objects.get(openid=openid)

        except:
            # 未绑定
            tjs=TJS(settings.SECRET_KEY,300)
            data={'openid':openid}
            access_token=tjs.dumps(data).decode()
            return Response({'access_token':access_token})

        # 绑定过跳转到登录成功页面
        # 获取user用户
        user=qq_oauth.user

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response(
            {
                'token':token,
                'username':user.username,
                'user_id':user.id
            }
        )




    # post请求，处理绑定openid业务逻辑　　　　其实这里很像creatＡＰＩVIEW





